/*
Given a binary tree, find its minimal depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
*/


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode *root) {
        if (!root) return 0;
        int mindepth = INT_MAX;
        minDepthHelper(root, 0, mindepth);
        return mindepth;
    }
private:
    void minDepthHelper(TreeNode *root, int curdepth, int &mindepth) {
        if (!root->left && !root->right) {  // leaf node
            if (++curdepth < mindepth) mindepth = curdepth;
            return;
        }
        if (root->left) minDepthHelper(root->left, curdepth+1, mindepth);
        if (root->right) minDepthHelper(root->right, curdepth+1, mindepth);
    }
};

